import 'package:flutter/material.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/assessments.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/evaluation.dart';
import 'package:ichinesereader/controller/reports.dart';
import 'package:ichinesereader/models/assessment/assessmentRecordsResult.dart';
import 'package:ichinesereader/pages/teacher/evaluationBookReport.dart';
import 'package:ichinesereader/pages/teacher/evaluationRecordReview.dart';
import 'package:ichinesereader/pages/teacher/evaluationReportPreview.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:intl/intl.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';

//import '../../themes/appTheme.dart';
import '../../themes/appTheme.dart';
import '../../themes/pageStyles.dart';

// ignore: must_be_immutable
class TestDataRecordGrids extends StatelessWidget {
  TestDataRecordGrids(this.evaluationRecordItems, this.isTeacher, this.mode);

  List<QuestionRecord> evaluationRecordItems;
  bool isTeacher = false;
  String mode = 'evaluation';

  bool isWebOrDesktop =
      GetPlatform.isMacOS || GetPlatform.isWeb || GetPlatform.isDesktop;
  List<DataGridRow> dataGridRows = <DataGridRow>[];

  DataGridController _dataGridController = DataGridController();

  final box = Hive.box('appconfig');
  final PageStyles _pageStyles = PageStyles();

  @override
  Widget build(BuildContext context) {
    Log.debug(mode);
    Log.debug('build evaluation records DataGrids');
    return Expanded(child: _buildDataGrid());
  }

  Container _buildDataGrid() {
    return Container(
      decoration: _pageStyles.dataGridBackground(),
      child: Container(
        margin: EdgeInsets.all(12),
        decoration: _pageStyles.dataGridForground(),
        child: SfDataGrid(
          source:
              QuizbookDataGridSource(items: evaluationRecordItems, mode: mode),
          isScrollbarAlwaysShown: true,
          onQueryRowHeight: (row) {
            return row.rowIndex == 0 ? 50.0 : 49.0;
          },
          //设置表头高度
          controller: _dataGridController,
          checkboxColumnSettings: Get.isDarkMode
              ? DataGridCheckboxColumnSettings(
                  backgroundColor: Color(0xff0a0e21),
                )
              : DataGridCheckboxColumnSettings(
                  backgroundColor: Colors.blue[50]),
          allowSorting: true,
          allowTriStateSorting: true,
          allowFiltering: true,
          selectionMode: SelectionMode.single,
          navigationMode: GridNavigationMode.row,
          endSwipeActionsBuilder:
              (BuildContext context, DataGridRow row, int rowIndex) {
            return GestureDetector(
                onTap: () {},
                child: Container(
                    color: Colors.redAccent,
                    child: Center(
                      child: Icon(Icons.delete),
                    )));
          },
          columns: <GridColumn>[
            GridColumn(
              width: isWebOrDesktop ? 250 : 220,
              columnName: 'Title',
              label: buildDataGridColumnLabel('Title'),
            ),
            GridColumn(
              columnName: 'Type',
              //allowFiltering: false,
              width: isWebOrDesktop ? 180 : 180,
              label: buildDataGridColumnLabel('Type'),
            ),
            GridColumn(
              width: isWebOrDesktop ? 160 : 140,
              columnName: 'Username',
              visible: isTeacher ? true : false,
              label: buildDataGridColumnLabel('UserName'),
            ),
            GridColumn(
              columnName: 'Text',
              allowFiltering: false,
              width: isWebOrDesktop ? 140.0 : 120.0,
              label: buildDataGridColumnLabel('Text'),
            ),
            GridColumn(
              columnName: 'Audio',
              allowFiltering: false,
              width: isWebOrDesktop ? 140.0 : 120.0,
              label: buildDataGridColumnLabel('Audio'),
            ),
            GridColumn(
              columnName: 'Status',
              allowFiltering: false,
              width: isWebOrDesktop ? 150 : 120,
              label: buildDataGridColumnLabel('Status'),
            ),
            GridColumn(
                columnName: 'Download',
                allowFiltering: false,
                allowSorting: false,
                width: 100,
                label: buildDataGridColumnLabel('Download')),
            GridColumn(
              columnName: 'LastUpdated',
              allowFiltering: false,
              width: 160,
              label: buildDataGridColumnLabel('LastUpdated'),
            ),
            GridColumn(
              columnName: 'BookCode',
              allowFiltering: false,
              width: 5,
              visible: false,
              label: buildDataGridColumnLabel('BookCode'),
            ),
            GridColumn(
              columnName: 'QuestionGroupId',
              allowFiltering: false,
              width: 5,
              visible: false,
              label: buildDataGridColumnLabel('QuestionGroupId'),
            ),
            GridColumn(
              columnName: 'QuestionLevel',
              allowFiltering: false,
              width: 5,
              visible: false,
              label: buildDataGridColumnLabel('QuestionLevel'),
            ),
            GridColumn(
              columnName: 'Id',
              allowFiltering: false,
              width: 5,
              visible: false,
              label: buildDataGridColumnLabel('Id'),
            ),
            GridColumn(
              columnName: 'Mode',
              visible: false,
              label: Text(''),
            ),
          ],
        ),
      ),
    );
  }
}

class QuizbookDataGridSource extends DataGridSource {
  QuizbookDataGridSource(
      {required List<QuestionRecord> items, required String mode}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<String>(
                  columnName: 'Title', value: dataGridRow.questionGroup?.title),
              DataGridCell<String>(columnName: 'Type', value: dataGridRow.type),
              DataGridCell<String>(
                  columnName: 'Username', value: dataGridRow.userName),
              DataGridCell<String>(
                  columnName: 'Text', value: dataGridRow.textType),
              DataGridCell<String>(
                  columnName: 'Audio', value: dataGridRow.audioType),
              DataGridCell<String>(
                  columnName: 'Status',
                  value: dataGridRow.status?.toUpperCase()),
              DataGridCell<int>(
                  columnName: "Download",
                  value: dataGridRow.questionGroup?.level),
              DataGridCell<int>(
                  columnName: 'LastUpdated', value: dataGridRow.committedTime),
              DataGridCell<String>(
                  columnName: 'BookCode',
                  value: dataGridRow.questionGroup?.bookId != null
                      ? dataGridRow.questionGroup?.bookId
                      : ''),
              DataGridCell<String>(
                  columnName: 'QuestionGroupId',
                  value: dataGridRow.questionGroup?.id != null
                      ? dataGridRow.questionGroup?.id
                      : ''),
              DataGridCell<int>(
                  columnName: 'QuestionLevel',
                  value: dataGridRow.questionGroup?.level),
              DataGridCell<String>(columnName: 'Id', value: dataGridRow.id),
              DataGridCell<String>(columnName: 'Mode', value: mode),
            ]))
        .toList();
  }

  List<DataGridRow> dataGridRows = [];
  final box = Hive.box('appconfig');
  AssessmentsController _assessmentController = Get.find();
  EvaluationController _evaluationController = Get.find();

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    Color setRowBackgroundColor() {
      final int index = effectiveRows.indexOf(row);
      if (index % 2 != 0) {
        return Get.isDarkMode ? Colors.black : Colors.grey[200]!;
      }
      return Colors.transparent;
    }

    bool isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher;
    String _classId = box.get(CacheManagerKey['currentclass'].toString());

    return DataGridRowAdapter(
        color: setRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          if (dataGridCell.columnName == 'LastUpdated') {
            if (dataGridCell.value > 0) {
              return Container(
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                    DateFormat('yyyy-MM-dd kk:mm').format(
                        DateTime.fromMillisecondsSinceEpoch(
                            dataGridCell.value)),
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(fontFamily: 'Noto Sans SC'),
                  ));
            } else {
              return Container(
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                    '',
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(fontFamily: 'Noto Sans SC'),
                  ));
            }
          } else if (dataGridCell.columnName == 'Status') {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: GestureDetector(
                  onTap: () {
                    var status = row
                        .getCells()
                        .where((element) => element.columnName == 'Status')
                        .first
                        .value;
                    var title = row
                        .getCells()
                        .where((element) => element.columnName == 'Title')
                        .first
                        .value;
                    var recordId = row
                        .getCells()
                        .where((element) => element.columnName == 'Id')
                        .first
                        .value;
                    var userName = row
                        .getCells()
                        .where((element) => element.columnName == 'Username')
                        .first
                        .value;
                    var type = row
                        .getCells()
                        .where((element) => element.columnName == 'Type')
                        .first
                        .value;
                    int level = row
                        .getCells()
                        .where(
                            (element) => element.columnName == 'QuestionLevel')
                        .first
                        .value;
                    String mode = row
                        .getCells()
                        .where((element) => element.columnName == 'Mode')
                        .first
                        .value;
                    _assessmentController.clearAssessmentQuestionRecordInfo();

                    if (isTeacher) {
                      // Get.to(() => InAppWebViewTeacherQuzibookReviewScreen(
                      //     type: type, username: username, questionId: recordId));
                      if (status == 'COMPLETED') {
                        _assessmentController
                            .fetchAssessmentRecordGrading(recordId);
                      }
                      box.put('evaluationRecordLevel', level);
                      _assessmentController
                          .fetchAssessmentRecordInfoDetails(recordId);
                      Get.to(() => EvaluationRecordReviewPage(), arguments: {
                        'title': title,
                        'status': status,
                        'recordId': recordId,
                        'userName': userName,
                        'assessmentType': type
                      })?.then((value) {
                        if (value != null && value['isRefresh'] == true) {
                          var classId = box
                              .get(CacheManagerKey['currentclass'].toString());
                          if (mode == 'evaluation') {
                            EvaluationController _controller = Get.find();
                            _controller.fetchEvaluationRecords(
                                '0', '0', '', classId);
                          } else if (mode == 'quickReview') {
                            ReportsController _reportsController = Get.find();
                            _reportsController.fetchLibraryRecords(_classId);
                          } else if (mode == 'quizBook') {
                            ReportsController _reportsController = Get.find();
                            _reportsController.getQuizBookRecordsByClass(
                                classId, "", "", "");
                          }
                        }
                      });
                    } else {
                      if (status == 'COMPLETED') {
                        _assessmentController
                            .fetchAssessmentRecordGrading(recordId);
                      }
                      _assessmentController
                          .fetchAssessmentRecordInfoDetails(recordId);
                      Get.to(() => EvaluationRecordReviewPage(), arguments: {
                        'title': title,
                        'status':
                            status == 'COMPLETED' ? 'COMPLETED' : 'UNDONE',
                        'assessmentType': type
                      });
                    }
                  },
                  child: Text(
                    dataGridCell.value,
                    style: TextStyle(
                      fontFamily: 'Noto Sans SC',
                      color: Get.theme.primaryColorDark,
                    ),
                    overflow: TextOverflow.fade,
                  ),
                ));
          } else if (dataGridCell.columnName == "Download") {
            var type = row
                .getCells()
                .where((element) => element.columnName == 'Type')
                .first
                .value;
            bool isBenchmark = type == Constants.AssessmentType_BENCHMARK_TEST;
            return IconButton(
              iconSize: 30,
              padding: EdgeInsets.zero,
              icon: Get.isDarkMode
                  ? Icon(Icons.download,
                      color: isBenchmark ? Colors.white : Colors.transparent)
                  : Icon(Icons.download,
                      color: isBenchmark
                          ? AppTheme.colors.addBtn
                          : Colors.transparent),
              onPressed: () {
                if (isBenchmark) {
                  var userName = row
                      .getCells()
                      .where((element) => element.columnName == 'Username')
                      .first
                      .value;
                  _evaluationController
                      .fetchBenchmarkReportUserData(
                          userName, dataGridCell.value.toString())
                      .then((value) {
                    if (value.studentName != null) {
                      Get.to(() => EvaluationReportPreview(
                            reportData: value,
                            level: dataGridCell.value,
                          ));
                    }
                  });
                }
              },
            );
          } else if (dataGridCell.columnName == 'Title') {
            var type = row
                .getCells()
                .where((element) => element.columnName == 'Type')
                .first
                .value;

            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: GestureDetector(
                  onTap: () {
                    var bookcode = row
                        .getCells()
                        .where((element) => element.columnName == 'BookCode')
                        .first
                        .value;
                    var booktitle = row
                        .getCells()
                        .where((element) => element.columnName == 'Title')
                        .first
                        .value;

                    if (bookcode != '') {
                      if (isTeacher && type == 'EVALUATION') {
                        _evaluationController.fetchEvaluationBookReportData(
                            _classId, bookcode);
                        Get.to(() => EvaluationBookReportForTeacher(
                              bookTitle: booktitle,
                              type: type,
                            ));
                      }
                    }
                  },
                  child: Text(
                    dataGridCell.value,
                    style: type == 'EVALUATION' && isTeacher
                        ? TextStyle(
                            fontFamily: 'Noto Sans SC',
                            color: Get.theme.primaryColorDark,
                          )
                        : Get.textTheme.bodySmall,
                    overflow: TextOverflow.fade,
                  ),
                ));
          } else {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  dataGridCell.value.toString(),
                  overflow: TextOverflow.fade,
                  style: Get.textTheme.bodySmall,
                ));
          }
        }).toList());
  }
}
